#!/usr/bin/node

const http = require('http'),
      log = console.log,
      qs = require('querystring'),
      fs = require('fs');

let items = ['eat','sleep'];

//返回的json数据
let result = {
  status:200,
  reason:'ok',
  //count:0,
  //date:[],
}


http.createServer((req,res)=>{
  logRequest(req);

  if(req.url.slice(0,5)!=='/todo') {
    let html = fs.readFileSync('./12-todo.html').toString('utf8');
    if(req.url === '/'){
      res.end(html);
    }else if(req.url == '/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);
    }else{
      res.end('not api request and not page request');
    }
    return;
  }


  switch(req.method){
    case  'GET':
      select(req,res);
      //res.end('get method');
      break;
    case 'POST':
      insert(res,req);
      //res.end('post method');
      break;
    case 'PUT':
      update(req,res);
      //res.end('put method');
      break;
    case 'DELETE':
      del(req,res)
        //res.end('delete method');
        break;
    default:
      res.end(`${res.method} method`);
      break;
  }
}).listen(3000);

function logRequest(req){
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('')
}

function select(req,res){
  result.data = items;
  //返回所有数据
  res.end(JSON.stringify(result));
}

function update(req,res){

  let id = req.url.split(':')[1];
  let data = '';
  req.on('data',chunk => data+=chunk);
  req.on('end',()=>{
    //update items[id]=item
    let item = qs.parse(data).item;

    if(item != '' && typeof item != 'undefined'){
      items[id] = item;
      res.end(result);
    }else{
      result.status = 402;
      res.end(req.method);
    }

  })
}

function insert(req,res){
  let data = '';
  res.on('data', chunk => data += chunk);
  res.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !== '' && typeof(item) !== undefined){
      items.push(item); 
      result.data = items;
      res.end(JSON.stringify(result));

    }else{
      result.status = 401;
      result.reason = 'item is empty';

      res.end(JSON.stringify(result));
    }
  })
}

function del(req,res){
  //id not exist del all
  //get id
  let id = req.url.split(';')[1];
  //id not exist: del all
  if(typeof id === 'undefined'){
    items = [];
    result.status = 200;
    result.reason = 'delete all successfully';
    res.end(JSON.stringify(result));
    return;
  }
  //id exist: del id 
  items = items.splice(id,1);
  result.status = 200;
  result.reason = 'del id successfully';
  res.end(JSON.stringify(result));

}
